package mh.demo.jdk.util.concurrent;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.Future;
import java.util.concurrent.RecursiveTask;

public class ForkJoinPoolDemo {
    private static class CountTask extends RecursiveTask<Integer> {
        private static final int THRESHOLD = 10;
        private final int start;
        private final int end;

        public CountTask(int start, int end) {
            this.start = start;
            this.end = end;
        }

        @Override
        protected Integer compute() {
            int sum = 0;
            if ((end - start) <= THRESHOLD) {
                for (int j = start; j <= end; j++) {
                    sum += j;
                }
            } else {
                int mid = (start + end) / 2;
                CountTask left = new CountTask(start, mid);
                CountTask right = new CountTask(mid + 1, end);
                left.fork();
                right.fork();
                sum = left.join() + right.join();
            }
            return sum;
        }
    }

    public static void main(String[] args) {
        ForkJoinPool pool = new ForkJoinPool();
        Future<Integer> result = pool.submit(new CountTask(1, 100));
        try {
            System.out.println(result.get());
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        }
    }
}
